{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:@react-spectrum/checkbox';
import packageData from '@react-spectrum/checkbox/package.json';
import {HeaderInfo, PropTable, PageDescription, VersionBadge, ClassAPI} from '@react-spectrum/docs';

```jsx import
 import {Checkbox, CheckboxGroup} from '@react-spectrum/checkbox';
 import {Flex} from '@react-spectrum/layout';
 ```

---
category: Forms
keywords: [input, checkbox group, accessibility]
after_version: 3.1.0
---

# CheckboxGroup

<PageDescription>{docs.exports.CheckboxGroup.description}</PageDescription>

<HeaderInfo
 packageData={packageData}
 componentNames={['CheckboxGroup', 'Checkbox']}
 sourceData={[
 {type: 'Spectrum', url: 'https://spectrum.adobe.com/page/checkbox/'}
 ]}
 since="3.0.0" />

## Example

```tsx example
<CheckboxGroup label="Favorite sports">
  <Checkbox value="soccer">Soccer</Checkbox>
  <Checkbox value="baseball">Baseball</Checkbox>
  <Checkbox value="basketball">Basketball</Checkbox>
</CheckboxGroup>
```

## Content

CheckboxGroup accepts multiple [Checkbox](Checkbox.html) elements as children.
Each Checkbox represents an option that can be selected, labeled by its children.

## Value

CheckboxGroup supports selecting zero or more items. An initial, uncontrolled value can be provided to the CheckboxGroup using the `defaultValue` prop.
Alternatively, a controlled value can be provided using the `value` prop. Both of these props accept an array of selected items, which map to the
`value` prop on each item.

```tsx example
function Example() {
  let [selected, setSelected] = React.useState(['soccer', 'baseball']);

  return (
    <Flex gap="size-300">
      <CheckboxGroup label="Favorite sports (uncontrolled)" defaultValue={['soccer', 'baseball']}>
        <Checkbox value="soccer">Soccer</Checkbox>
        <Checkbox value="baseball">Baseball</Checkbox>
        <Checkbox value="basketball">Basketball</Checkbox>
      </CheckboxGroup>

      <CheckboxGroup label="Favorite sports (controlled)" value={selected} onChange={setSelected}>
        <Checkbox value="soccer">Soccer</Checkbox>
        <Checkbox value="baseball">Baseball</Checkbox>
        <Checkbox value="basketball">Basketball</Checkbox>
      </CheckboxGroup>
    </Flex>
  );
}
```

### HTML forms

CheckboxGroup supports the `name` prop, paired with the Checkbox `value` prop, for integration with HTML forms.

```tsx example
<CheckboxGroup label="Condiments" name="condiments">
  <Checkbox value="mayo">Mayo</Checkbox>
  <Checkbox value="mustart">Mustard</Checkbox>
  <Checkbox value="ketchup">Ketchup</Checkbox>
</CheckboxGroup>
```

## Labeling
A visual label should be provided for the CheckboxGroup using the `label` prop. If the CheckboxGroup requires an option to be selected by the user,
the `isRequired` and `necessityIndicator` props can be used to show a required state.

```tsx example
<Flex gap="size-300" wrap>
  <CheckboxGroup label="Favorite sports">
    <Checkbox value="soccer">Soccer</Checkbox>
    <Checkbox value="baseball">Baseball</Checkbox>
    <Checkbox value="basketball">Basketball</Checkbox>
  </CheckboxGroup>
  <CheckboxGroup label="Favorite sports" isRequired necessityIndicator="icon">
    <Checkbox value="soccer">Soccer</Checkbox>
    <Checkbox value="baseball">Baseball</Checkbox>
    <Checkbox value="basketball">Basketball</Checkbox>
  </CheckboxGroup>
  <CheckboxGroup label="Favorite sports" isRequired necessityIndicator="label">
    <Checkbox value="soccer">Soccer</Checkbox>
    <Checkbox value="baseball">Baseball</Checkbox>
    <Checkbox value="basketball">Basketball</Checkbox>
  </CheckboxGroup>
  <CheckboxGroup label="Favorite sports" necessityIndicator="label">
    <Checkbox value="soccer">Soccer</Checkbox>
    <Checkbox value="baseball">Baseball</Checkbox>
    <Checkbox value="basketball">Basketball</Checkbox>
  </CheckboxGroup>
</Flex>
```

### Accessibility

If a visible label isn't specified for a CheckboxGroup, an `aria-label` must be provided for accessibility. If the field is labeled by a separate element, an `aria-labelledby` prop must be provided using the id of the labeling element instead.

Checkbox elements within a group should always have a visible label.

### Internationalization

To internationalize a CheckboxGroup, a localized string should be passed to the `label` prop and as the child content of the Checkbox elements.
For languages that are read right-to-left (e.g. Hebrew and Arabic), the Checkbox is automatically placed on the right side of the text. When the necessityIndicator prop is set to "label", a localized string will be provided for "(required)" or "(optional)" automatically.

## Events

CheckboxGroup accepts an `onChange` prop, which is triggered when a user adds or removes an item from the selection.
The example below uses `onChange` to log how the user is interacting with the component.

```tsx example
function Example() {
  let [selected, setSelected] = React.useState([]);

  return (
    <>
      <CheckboxGroup label="Favorite sports" value={selected} onChange={setSelected}>
        <Checkbox value="soccer">Soccer</Checkbox>
        <Checkbox value="baseball">Baseball</Checkbox>
        <Checkbox value="basketball">Basketball</Checkbox>
      </CheckboxGroup>
      <div>You have selected: {selected.join(', ')}</div>
    </>
  );
}
```

## Validation

CheckboxGroup supports the `isRequired` prop to ensure the user selects at least one item, as well as custom client and server-side validation. Individual checkboxes also support validation, and errors from all checkboxes are aggregated at the group level. CheckboxGroup can also be integrated with other form libraries. See the [Forms](../forms) guide to learn more.

### Group validation

The `isRequired` prop at the `CheckboxGroup` level requires that at least one item is selected. When the [Form](Form.html) component has the `validationBehavior="native"` prop, validation errors block form submission and are displayed as help text automatically.

```tsx example
import {Form, ButtonGroup, Button} from '@adobe/react-spectrum';

<Form validationBehavior="native">
  {/*- begin highlight -*/}
  <CheckboxGroup label="Sandwich condiments" name="condiments" isRequired>
  {/*- end highlight -*/}
    <Checkbox value="lettuce">Lettuce</Checkbox>
    <Checkbox value="tomato">Tomato</Checkbox>
    <Checkbox value="onion">Onion</Checkbox>
    <Checkbox value="sprouts">Sprouts</Checkbox>
  </CheckboxGroup>
  <ButtonGroup>
    <Button type="submit" variant="primary">Submit</Button>
    <Button type="reset" variant="secondary">Reset</Button>
  </ButtonGroup>
</Form>
```

By default, `CheckboxGroup` displays default validation messages provided by the browser. See [Customizing error messages](../forms#customizing-error-messages) in the Forms guide to learn how to provide your own custom errors.

### Individual Checkbox validation

To require that specific checkboxes are checked, set the `isRequired` prop at the `Checkbox` level instead of the `CheckboxGroup`. The following example shows how to require that all items are selected.

```tsx example
<Form validationBehavior="native">
  <CheckboxGroup label="Agree to the following" isRequired>
    {/*- begin highlight -*/}
    <Checkbox value="terms" isRequired>Terms and conditions</Checkbox>
    <Checkbox value="privacy" isRequired>Privacy policy</Checkbox>
    <Checkbox value="cookies" isRequired>Cookie policy</Checkbox>
    {/*- end highlight -*/}
  </CheckboxGroup>
  <ButtonGroup>
    <Button type="submit" variant="primary">Submit</Button>
    <Button type="reset" variant="secondary">Reset</Button>
  </ButtonGroup>
</Form>
```

## Props

<PropTable component={docs.exports.CheckboxGroup} links={docs.links} />

## Visual options

### Orientation

CheckboxGroups are vertically oriented by default.
The `orientation` prop can be used to change the orientation to horizontal.

```tsx example
<CheckboxGroup label="Favorite sports" orientation="horizontal">
  <Checkbox value="soccer">Soccer</Checkbox>
  <Checkbox value="baseball">Baseball</Checkbox>
  <Checkbox value="basketball">Basketball</Checkbox>
</CheckboxGroup>
```

### Label position and alignment

By default, the label is positioned above the CheckboxGroup.
The `labelPosition` prop can be used to position the label to the side. The `labelAlign` prop can
be used to align the label as "start" or "end".
For left-to-right (LTR) languages, "start" refers to the left most edge of the CheckboxGroup
and "end" refers to the right most edge. For right-to-left (RTL) languages, this is flipped.

```tsx example
<CheckboxGroup label="Favorite sports" labelPosition="side" labelAlign="end">
  <Checkbox value="soccer">Soccer</Checkbox>
  <Checkbox value="baseball">Baseball</Checkbox>
  <Checkbox value="basketball">Basketball</Checkbox>
</CheckboxGroup>
```

### Help text
[View guidelines](https://spectrum.adobe.com/page/checkbox-group/#Help-text-(description-and-error-message))

Both a description and an error message can be supplied to a CheckboxGroup. The description is always visible unless the `isInvalid` is true and an error message is provided. The error message can be used to help the user fix their input quickly and should be specific to the detected error. All strings should be localized.

```tsx example
function Example() {
  let [checked, setChecked] = React.useState(['dogs', 'dragons']);
  let isValid = checked.length === 2 && checked.includes('dogs') && checked.includes('dragons');

  return (
    <CheckboxGroup
      label="Pets"
      onChange={setChecked}
      value={checked}
      isInvalid={!isValid}
      description="Select your pets."
      errorMessage={
        checked.includes('cats')
          ? 'No cats allowed.'
          : 'Select only dogs and dragons.'
      }>
      <Checkbox value="dogs">Dogs</Checkbox>
      <Checkbox value="cats">Cats</Checkbox>
      <Checkbox value="dragons">Dragons</Checkbox>
    </CheckboxGroup>
  );
}
```

### Contextual help

A [ContextualHelp](ContextualHelp.html) element may be placed next to the label to provide additional information or help about a CheckboxGroup.

```tsx example
import {Content, ContextualHelp, Heading} from '@adobe/react-spectrum';

<CheckboxGroup
  label="Favorite genres"
  contextualHelp={
    <ContextualHelp>
      <Heading>What does this do?</Heading>
      <Content>Your musical taste is used to train our machine learning recommendation algorithm.</Content>
    </ContextualHelp>
  }>
  <Checkbox value="rock">Rock</Checkbox>
  <Checkbox value="pop">Pop</Checkbox>
  <Checkbox value="classical">Classical</Checkbox>
</CheckboxGroup>
```

### Disabled
[View guidelines](https://spectrum.adobe.com/page/checkbox/#Disabled)

```tsx example
<CheckboxGroup label="Favorite sports" isDisabled>
  <Checkbox value="soccer">Soccer</Checkbox>
  <Checkbox value="baseball">Baseball</Checkbox>
  <Checkbox value="basketball">Basketball</Checkbox>
</CheckboxGroup>
```

```tsx example
<CheckboxGroup label="Favorite sports">
  <Checkbox value="soccer">Soccer</Checkbox>
  <Checkbox value="baseball" isDisabled>Baseball</Checkbox>
  <Checkbox value="basketball">Basketball</Checkbox>
</CheckboxGroup>
```

### Read only
[View guidelines](https://spectrum.adobe.com/page/checkbox/#Read-only)

The `isReadOnly` prop makes the selection immutable. Unlike `isDisabled`, the CheckboxGroup remains focusable.
See the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly) for more information.

```tsx example
<CheckboxGroup label="Favorite sports" defaultValue={['baseball']} isReadOnly>
  <Checkbox value="soccer">Soccer</Checkbox>
  <Checkbox value="baseball">Baseball</Checkbox>
  <Checkbox value="basketball">Basketball</Checkbox>
</CheckboxGroup>
```

### Emphasized
[View guidelines](https://spectrum.adobe.com/page/checkbox/#Emphasis)

```tsx example
<CheckboxGroup label="Favorite sports" defaultValue={['soccer', 'baseball']} isEmphasized>
  <Checkbox value="soccer">Soccer</Checkbox>
  <Checkbox value="baseball">Baseball</Checkbox>
  <Checkbox value="basketball">Basketball</Checkbox>
</CheckboxGroup>
```
